package org.ph.share.race;

/**
 * 龟兔赛跑场景复现</p>
 *
 * @author Hush.
 * @since 2023/03/30 15:16
 */
public class TortoiseAndHareRace implements Runnable {
    private static final String rabbit = "兔子";
    private static final String turtle = "乌龟";

    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 10000; i++) {
            String name = Thread.currentThread().getName();
            System.out.println(name + "-->第" + i + "步");
            //模拟兔子中途睡觉
            if (name.equals(rabbit) && i != 0 && i % 9 == 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (gameOver(i)) {
                break;
            }
        }
    }

    /**
     * 判断是否结束比赛（）
     */
    private boolean gameOver(int step) {
        if (winner != null) {
            return true;
        }
        if (step == 10000) {
            winner = Thread.currentThread().getName();
            System.out.println("游戏结束！获胜方：" + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TortoiseAndHareRace race = new TortoiseAndHareRace();
        new Thread(race, rabbit).start();
        new Thread(race, turtle).start();
    }
}
